package com.sls.mall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.rabbitmq.client.Channel;
import com.sls.common.exception.NoStockException;
import com.sls.common.to.mq.OrderTo;
import com.sls.common.to.mq.SeckillOrderTo;
import com.sls.common.utils.R;
import com.sls.common.vo.MemberRespVo;
import com.sls.mall.order.constant.OrderConstant;
import com.sls.mall.order.constant.PayConstant;
import com.sls.mall.order.entity.OmsOrderItemEntity;
import com.sls.mall.order.entity.OmsOrderReturnReasonEntity;
import com.sls.mall.order.entity.OmsPaymentInfoEntity;
import com.sls.mall.order.enume.OrderStatusEnum;
import com.sls.mall.order.feign.CartFeignService;
import com.sls.mall.order.feign.MemberFeignService;
import com.sls.mall.order.feign.ProductFeignService;
import com.sls.mall.order.feign.WmsFeignService;
import com.sls.mall.order.interceptor.LoginInterceptor;
import com.sls.mall.order.service.OmsOrderItemService;
import com.sls.mall.order.service.OmsPaymentInfoService;
import com.sls.mall.order.to.OrderCreateTo;
import com.sls.mall.order.vo.*;
import com.sls.mall.ware.vo.LockStockResultVo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sls.common.utils.PageUtils;
import com.sls.common.utils.Query;

import com.sls.mall.order.dao.OmsOrderDao;
import com.sls.mall.order.entity.OmsOrderEntity;
import com.sls.mall.order.service.OmsOrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@RabbitListener(queues = {"hello-queue"})
@Service("omsOrderService")
public class OmsOrderServiceImpl extends ServiceImpl<OmsOrderDao, OmsOrderEntity> implements OmsOrderService {

    public static ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Autowired
    OmsOrderItemService orderItemService;
    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    WmsFeignService wmsFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    OmsPaymentInfoService paymentInfoService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OmsOrderEntity> page = this.page(
                new Query<OmsOrderEntity>().getPage(params),
                new QueryWrapper<OmsOrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirm() {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginInterceptor.threadLocal.get();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();// 主线程请求头

        // 通过线程池获取收货地址
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);// 当前线程放入之前的请求头数据
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            confirmVo.setAddress(address);
        }, executor);

        // 获取用户购物车数据
        CompletableFuture<Void> getCartItemFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);// 当前线程放入之前的请求头数据
            List<OrderItemVo> cartItems = cartFeignService.getCurrentCartItems();
            confirmVo.setItems(cartItems);
        }, executor).thenRunAsync(()->{
            RequestContextHolder.setRequestAttributes(requestAttributes);// 当前线程放入之前的请求头数据
            //获取产品库存
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R hasStock = wmsFeignService.getSkusHasStock(collect);
            if(hasStock != null){
                List<SkuHasStockVo> data = hasStock.getData(new TypeReference<List<SkuHasStockVo>>() {
                });
                if(data != null){
                    Map<Long, Boolean> hasStockMap = data.stream().collect(Collectors.toMap(k -> k.getSkuId(), v -> v.getHasStock()));

                    List<OrderItemVo> collect1 = items.stream().map(item -> {
                        item.setHasStock(hasStockMap.get(item.getSkuId()));
                        return item;
                    }).collect(Collectors.toList());
                    confirmVo.setItems(collect1);
                }
            }
        },executor);

        // 获取用户积分
        confirmVo.setIntegration(memberRespVo.getIntegration());
        // 防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");

        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token, 30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);

        try {
            CompletableFuture.allOf(getAddressFuture, getCartItemFuture).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return confirmVo;
    }

    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        MemberRespVo memberRespVo = LoginInterceptor.threadLocal.get();
        confirmVoThreadLocal.set(vo);
        // 1.验证令牌
        String orderToken = vo.getOrderToken();
        // redis 脚本保证查询和删除原子性，预防多线程同时调用
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        if(result == 0L){
            // 令牌校验不通过
            responseVo.setCode(1);
        } else {
            // 校验通过
            //1、创建订单、订单项等信息
            OrderCreateTo order = createOrder();

            //2.验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if(Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01){
                //验价通过
                //3.保存订单
                savaOrder(order);

                //4.锁定库存
                WareSkuLockVo skuLockVo = new WareSkuLockVo();
                skuLockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> collect = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setTitle(item.getSkuName());
                    itemVo.setCount(item.getSkuQuantity());
                    return itemVo;
                }).collect(Collectors.toList());
                skuLockVo.setLocks(collect);
                //出现的问题：扣减库存成功了，但是由于网络原因超时，出现异常，导致订单事务回滚，库存事务不回滚(解决方案：seata)
                //为了保证高并发，不推荐使用seata，因为是加锁，并行化，提升不了效率,可以发消息给库存服务
                R r = wmsFeignService.orderLockStock(skuLockVo);
                if(r != null && r.getCode() == 0){
                    // 库存锁定成功
                    responseVo.setCode(0);
                    responseVo.setOrder(order.getOrder());
//                    int i = 10/0;
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order", order.getOrder());
               } else {
                    //锁定失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }
            } else {
                responseVo.setCode(2);
                return responseVo;
            }
        }
        return responseVo;
    }

    @Override
    public OmsOrderEntity getOrderByOrderSn(String orderSn) {
        OmsOrderEntity omsOrderEntity = baseMapper.selectOne(new QueryWrapper<OmsOrderEntity>().eq("order_sn", orderSn));
        return omsOrderEntity;
    }

    @Override
    public void closeOrder(OmsOrderEntity entity) {
        OmsOrderEntity orderEntity = this.getById(entity.getId());
        //未款状态进行关单
        if (orderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {
            OmsOrderEntity updateOrder = new OmsOrderEntity();
            updateOrder.setId(entity.getId());
            updateOrder.setOrderSn(orderEntity.getOrderSn());
            updateOrder.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(updateOrder);

            // 发送到库存解锁队列，因为订单创建时会有个过期自动解锁消息，由于会出现时间差（订单未关闭，库存定时任务先执行）加入主动通知解锁库存消息
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(updateOrder, orderTo);
            rabbitTemplate.convertAndSend("order-event-exchange","order.release.other.#", orderTo);
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        OmsOrderEntity order = this.getOrderByOrderSn(orderSn);
        PayVo payVo = new PayVo();
        payVo.setOut_trade_no(orderSn);
        BigDecimal bigDecimal = order.getPayAmount().setScale(2, RoundingMode.UP);
        payVo.setTotal_amount(bigDecimal.toString());

        List<OmsOrderItemEntity> list = orderItemService.list(new QueryWrapper<OmsOrderItemEntity>().eq("order_sn", orderSn));
        OmsOrderItemEntity itemEntity = list.get(0);
        payVo.setSubject(itemEntity.getSpuName());
        payVo.setBody(itemEntity.getSkuName());
        return payVo;
    }

    @Override
    public PageUtils listWithItem(Map<String, Object> pageMap) {
        MemberRespVo memberRespVo = LoginInterceptor.threadLocal.get();
        IPage<OmsOrderEntity> page = this.page(new Query<OmsOrderEntity>().getPage(pageMap), new QueryWrapper<OmsOrderEntity>().eq("member_id", memberRespVo.getId()));
        page.getRecords().stream().map(order ->{
            List<OmsOrderItemEntity> list = orderItemService.list(new QueryWrapper<OmsOrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntityList(list);
            return order;
        }).collect(Collectors.toList());

        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo asyncVo) {
        //保存交易流水信息
        OmsPaymentInfoEntity paymentInfo = new OmsPaymentInfoEntity();
        paymentInfo.setOrderSn(asyncVo.getOut_trade_no());
        paymentInfo.setAlipayTradeNo(asyncVo.getTrade_no());
        paymentInfo.setTotalAmount(new BigDecimal(asyncVo.getBuyer_pay_amount()));
        paymentInfo.setSubject(asyncVo.getBody());
        paymentInfo.setPaymentStatus(asyncVo.getTrade_status());
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setCallbackTime(asyncVo.getNotify_time());
        //添加到数据库中
        this.paymentInfoService.save(paymentInfo);

        //修改订单状态
        //获取当前状态
        String tradeStatus = asyncVo.getTrade_status();

        if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")) {
            //支付成功状态
            String orderSn = asyncVo.getOut_trade_no(); //获取订单号
            this.baseMapper.updateOrderStatus(orderSn,OrderStatusEnum.PAYED.getCode(), PayConstant.ALIPAY);
        }

        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo orderTo) {
        //TODO 保存订单信息
        OmsOrderEntity orderEntity = new OmsOrderEntity();
        orderEntity.setOrderSn(orderTo.getOrderSn());
        orderEntity.setMemberId(orderTo.getMemberId());
        orderEntity.setCreateTime(new Date());
        BigDecimal totalPrice = orderTo.getSeckillPrice().multiply(BigDecimal.valueOf(orderTo.getNum()));
        orderEntity.setPayAmount(totalPrice);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        //保存订单
        this.save(orderEntity);

        //保存订单项信息
        OmsOrderItemEntity orderItem = new OmsOrderItemEntity();
        orderItem.setOrderSn(orderTo.getOrderSn());
        orderItem.setRealAmount(totalPrice);

        orderItem.setSkuQuantity(orderTo.getNum());

        //保存商品的spu信息
        R spuInfo = productFeignService.getSpuInfoBySkuId(orderTo.getSkuId());
        SpuInfoVo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoVo>() {
        });
        orderItem.setSpuId(spuInfoData.getId());
        orderItem.setSpuName(spuInfoData.getSpuName());
        orderItem.setSpuBrand(spuInfoData.getBrandName());
        orderItem.setCategoryId(spuInfoData.getCatalogId());

        //保存订单项数据
        orderItemService.save(orderItem);
    }

    /**
     * 订单保存
     * @param order
     */
    private void savaOrder(OrderCreateTo order) {
        OmsOrderEntity orderEntity = order.getOrder();
        orderEntity.setCreateTime(new Date());
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OmsOrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);

    }

    /**
     * 创建订单
     * @return
     */
    private OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        String orderSn = IdWorker.getTimeId();
        OmsOrderEntity orderEntity = builderOrder(orderSn);

        //2、获取到所有的订单项
        List<OmsOrderItemEntity> orderItemEntities = builderOrderItems(orderSn);

        //3、验价(计算价格、积分等信息)
        computePrice(orderEntity,orderItemEntities);

        createTo.setOrder(orderEntity);
        createTo.setOrderItems(orderItemEntities);

        return createTo;
    }

    /**
     * 计算价格的方法
     * @param orderEntity
     * @param orderItemEntities
     */
    private void computePrice(OmsOrderEntity orderEntity, List<OmsOrderItemEntity> orderItemEntities) {
        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        //订单总额，叠加每一个订单项的总额信息
        for (OmsOrderItemEntity orderItem : orderItemEntities) {
            //优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());

            //总价
            total = total.add(orderItem.getRealAmount());

            //积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();

        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);

        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);

        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);
    }

    /**
     * 构建订单明细
     * @param orderSn
     * @return
     */
    private List<OmsOrderItemEntity> builderOrderItems(String orderSn) {
        List<OmsOrderItemEntity> orderItemEntityList = new ArrayList<>();

        //最后确定每个购物项的价格
        List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems();
        if (currentCartItems != null && currentCartItems.size() > 0) {
            orderItemEntityList = currentCartItems.stream().map((items) -> {
                //构建订单项数据
                OmsOrderItemEntity orderItemEntity = builderOrderItem(items);
                orderItemEntity.setOrderSn(orderSn);

                return orderItemEntity;
            }).collect(Collectors.toList());
        }

        return orderItemEntityList;
    }

    /**
     * 构建订单明细
     * @param items
     * @return
     */
    private OmsOrderItemEntity builderOrderItem(OrderItemVo items) {
        OmsOrderItemEntity orderItemEntity = new OmsOrderItemEntity();

        //1、商品的spu信息
        Long skuId = items.getSkuId();
        //获取spu的信息
        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfoData.getId());
        orderItemEntity.setSpuName(spuInfoData.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoData.getBrandName());
        orderItemEntity.setCategoryId(spuInfoData.getCatalogId());

        //2、商品的sku信息
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(items.getTitle());
        orderItemEntity.setSkuPic(items.getImage());
        orderItemEntity.setSkuPrice(items.getPrice());
        orderItemEntity.setSkuQuantity(items.getCount());

        //使用StringUtils.collectionToDelimitedString将list集合转换为String
        String skuAttrValues = StringUtils.collectionToDelimitedString(items.getSkuAttrValues(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrValues);

        //3、商品的优惠信息

        //4、商品的积分信息
        orderItemEntity.setGiftGrowth(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue());
        orderItemEntity.setGiftIntegration(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue());

        //5、订单项的价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);

        //当前订单项的实际金额.总额 - 各种优惠价格
        //原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);

        return orderItemEntity;
    }

    /**
     * 构建订单
     * @param orderSn
     * @return
     */
    private OmsOrderEntity builderOrder(String orderSn) {
        //获取当前用户登录信息
        MemberRespVo memberResponseVo = LoginInterceptor.threadLocal.get();

        OmsOrderEntity orderEntity = new OmsOrderEntity();
        orderEntity.setMemberId(memberResponseVo.getId());
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberUsername(memberResponseVo.getUsername());

        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();

        //远程获取收货地址和运费信息
        R fareAddressVo = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareResp = fareAddressVo.getData("data", new TypeReference<FareVo>() {});

        //获取到运费信息
        BigDecimal fare = fareResp.getFare();
        orderEntity.setFreightAmount(fare);

        //获取到收货地址信息
        MemberAddressVo address = fareResp.getAddress();
        //设置收货人信息
        orderEntity.setReceiverName(address.getName());
        orderEntity.setReceiverPhone(address.getPhone());
        orderEntity.setReceiverPostCode(address.getPostCode());
        orderEntity.setReceiverProvince(address.getProvince());
        orderEntity.setReceiverCity(address.getCity());
        orderEntity.setReceiverRegion(address.getRegion());
        orderEntity.setReceiverDetailAddress(address.getDetailAddress());

        //设置订单相关的状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setConfirmStatus(0);
        return orderEntity;
    }

    /**
     * queue:声明需要监听的所有队列
     * @param message 原生的消息详细信息，头+体
     * @param content T<发送的消息的类型>
     * @param channel 当前传输数据的通道
     *
     * Queue：可以由很多人监听，只要接收到消息，队列删除消息，而且只能有一个收到此消息
     * 场景：
     *     1）订单服务启动多个：同一个消息，只能有一个客户端收到
     *     2）只有一个消息完全处理完，方法运行结束，我们就可以接收到下一个消息
     */
//    @RabbitListener(queues = {"hello-queue"})
    @RabbitHandler
    public void recieveMessage(Message message, OmsOrderReturnReasonEntity content, Channel channel){
        byte[] body = message.getBody();
//        MessageProperties properties = message.getMessageProperties();
        System.out.println("接收到消息..."+message+"=>内容："+content);

        try{
            long deliveryTag = message.getMessageProperties().getDeliveryTag();
            if(deliveryTag %2 ==0){
                //签收货物，非批量模式
                channel.basicAck(deliveryTag, false);
            } else {
                // 拒签 requeue = false 丢弃  requeue=true 发回服务器，服务器重新入队
                channel.basicNack(deliveryTag, false, true);
            }

        }catch (Exception e){
            // 网络中断
        }

    }

}